﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Gqq.Csharpindepth.Chapter23
{
    public class Pair<T1, T2> : IEquatable<Pair<T1, T2>>
    {
        /// <summary>
        /// 其实，IEqualityComparer和ICompare极为相似
        /// 只不过返回值不同而已。
        /// 可以在new Dictionary(IEqualityComparer ic)中
        /// </summary>
        //Dictionary<string,int> d=new Dictionary<string,int>()
        public static readonly IEqualityComparer<T1> FirstComparer = EqualityComparer<T1>.Default;
        public static readonly IEqualityComparer<T2> SecondComparer = EqualityComparer<T2>.Default;

        /// <summary>
        /// 实现IEquatable中制定的Equals方法。
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public bool Equals(Pair<T1, T2> other)
        {
//            if (ReferenceEquals(null, other)) return false;
//            if (ReferenceEquals(this, other)) return true;
//            return Equals(other.first, first) && Equals(other.second, second);
            return other != null && FirstComparer.Equals(this.first, other.first) && SecondComparer.Equals(this.second, other.second);
        }

        public override bool Equals(object obj)
        {

            return Equals(obj as Pair<T1, T2>);
        }

        private readonly T1 first;
        private readonly T2 second;

        public Pair(T1 first, T2 second)
        {
            this.first = first;
            this.second = second;
        }

        public T1 First
        {
            get { return first; }
        }

        public T2 Second
        {
            get { return second; }
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (FirstComparer.GetHashCode() * 397) ^ SecondComparer.GetHashCode();
            }
        }
    }
}
